/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package k3tool.common.filter;

import java.io.File;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import k3tool.opf.model.TableOfContentItem;

/**
 *
 * @author Jeff Huang
 */
public class FileName2Toc {
    public static final Pattern ARTIFICIAL_ORDER_PATTERN = Pattern.compile("^[0-9]{3}-(.+)$");

    private SimpleTitleBuilder titleBuilder = new SimpleTitleBuilder(); //default

    public static String getRelativePath(File file, File baseDir){
        Stack<String> pathList = new Stack<String>();
        pathList.push(file.getName());
        File parent = file.getAbsoluteFile().getParentFile();
        baseDir = baseDir.getAbsoluteFile();
        while(parent != null){
            if(parent.equals(baseDir))
                break;
            pathList.push(parent.getName());
            parent = parent.getParentFile();
        }
        if(parent == null){
            throw new IllegalArgumentException(baseDir.getAbsolutePath() + " is not a parent of " + file.getAbsolutePath());
        }
        StringBuilder sb = new StringBuilder();
        String path;
        while(!pathList.isEmpty()){
            path = pathList.pop();
            sb.append("/");
            sb.append(path);
        }
        return sb.substring(1);
    }

    public TableOfContentItem makeItem(File file, File baseDir){
        TableOfContentItem item = new TableOfContentItem();
        item.setHref(getRelativePath(file, baseDir));

        item.setValue(titleBuilder.buildTitle(file));
        
        return item;
    }
}
